Twilight's Python Tutorial
by HoneyApple
Summary: Twilight ATTEMPTS to teach Pinkie and Dash how to program in python. Will she succeed?


"Now, pay attention Pinkie. And you too Dash" Twilight said, setting up the chalkboard in her library, where Pinkie and Rainbow Dash were.

"Here are the basics:

# Comment.  
variable=1 Variable='string'  
Literal is a representation of a value: 1, 'string'  
Variable - an object that holds the place of a value(numbers, strings, lists, etc.)

Delimiters ()

{}

:

` = ;

"

-  
Python data types:

-  
Boolean values (True, False) - The answers of whether something is true or not.

loopy_nums= (99,100,3,44,65,4)  
4 in loopy_nums True 1 in loopy_nums False

-  
None(None) - The answer that says that something is non existent, empty, or unknown.

-  
Numbers(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, etc.):

8**2 64 15/4 3 15./4 3.75 15/4.  
3.75 15.0/4.0 3.75

-  
Strings('text'):

'I said \'hi\''  
"I said 'hi'"  
"I said 'hi'"  
"I said 'hi'"  
'I said "hi"'  
'I said "hi"'

"tom's mom"  
"tom's mom"  
'tom\'s mom'  
"tom's mom"

"Tom\'s mom said 'Hi!'"  
"Tom's mom said 'Hi!'"  
"Tom's mom said 'Hi!'"  
"Tom's mom said 'Hi!'"

'Tom\'s mom said "Hi!"'  
'Tom\'s mom said "Hi!"'  
'Tom's mom said "Hi!"'  
SyntaxError: invalid syntax

indexing and Slicing:  
'funny'[2]  
'n'  
'funny'[0:4]  
'funn'

concatenating:  
'I love '+'to eat'+' food.'  
'I love to eat food.'

multiply:  
'The fast lane. '*3 'The fast lane. The fast lane. The fast lane. '

Variable in a string:  
Tortuse='I like to %s %s.'  
fill= ('eat','apples')  
print Tortuse % fill I like to eat apples.  
Tortuse % fill 'I like to eat apples.'

compare:  
"love""Hop"  
True 'Love''hop'  
False 'love''hop'  
True 'love'='love'  
True 'loop'='loopy'  
False -  
Lists([1,2,3],['a','b','c']) - An ordered sequence of values.

A_list=['a','b','c','d','e','f','g','h','i','j','k','l']  
A_list ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

Indexing:  
A_list[0]  
'a'  
A_list[11]  
'l'  
A_list[-1]  
'l'  
A_list[-8]  
'e'

Slicing:  
A_list[0:5]  
['a', 'b', 'c', 'd', 'e']  
A_list[5:0]

A_list[-9:-7]  
['d', 'e']  
A_list[-7:-9]  
[]

A_list[4:]  
['e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']  
A_list[:3]  
['a', 'b', 'c']  
A_list[:]  
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

A_list[2:10:3]  
['c', 'f', 'i']  
A_list[-9:-2:2]  
['d', 'f', 'h', 'j']  
A_list(6)

Traceback (most recent call last):  
File "pyshell#6", line 1, in module  
A_list(6)  
TypeError: 'list' object is not callable

concatenate:  
[6,8,456]+[9,9,6,7]  
[6, 8, 456, 9, 9, 6, 7]  
['8','k','jay']+['hey','is','hay','89']  
['8', 'k', 'jay', 'hey', 'is', 'hay', '89']  
[8,909]+['juy','55','monday']  
[8, 909, 'juy', '55', 'monday']  
['77','kay','key']+[8,45667,912]  
['77', 'kay', 'key', 8, 45667, 912]  
sting=['hit','me']  
looloo=[7,8]  
sting+looloo ['hit', 'me', 7, 8]

multiply:  
['h','L']*2 ['h', 'L', 'h', 'L']  
[7]*3 [7, 7, 7]

replacing:  
popa=[6,8,45,900,67]  
popa[1]=87 popa [6, 87, 45, 900, 67]  
santa=['toy','toys','land','doll','jay']  
santa[1:4]=['lovely','fabric']  
santa ['toy', 'lovely', 'fabric', 'jay']  
santa[2:2]=['haha','hoho']  
santa ['toy', 'lovely', 'haha', 'hoho', 'fabric', 'jay']  
santa[3:5]=[]  
santa ['toy', 'lovely', 'haha', 'jay']  
santa ['toy', 'lovely', 'haha', 'jay']  
santa[0:1]=[]  
santa ['lovely', 'haha', 'jay']

-  
Tuptes((1,2,3), ('a','b','c')) - an ordered sequence of values which cannot be changed using methods.

A_tupte= (1,-2,3,4,55,7,1000,8,0,122,-13,100)  
A_tupte(0)

Traceback (most recent call last):  
File "pyshell#1", line 1, in module  
A_tupte(0)  
TypeError: 'tuple' object is not callable A_tupte[6]  
1000

-  
Sets(set([1,2,7]),set(['a','e'])) - An unordered set of data, with no repeating values.  
Some oporations with sets:  
& intersection | union - difference ^ symmetric difference

SetA=set(['3','e','the','pop','10000000','+','-=\/'])  
SetB=set (['e','10000000','zzz','23','cuz I can'])  
SetA set(['10000000', 'e', '+', 'pop', '3', 'the', '-=\\/'])  
SetB set(['cuz I can', '10000000', 'e', 'zzz', '23'])  
SetB & SetA set(['10000000', 'e'])  
SetA|SetB set(['10000000', 'e', 'zzz', '23', 'cuz I can', '+', 'pop', '3', 'the', '-=\\/'])  
SetB-SetA set(['cuz I can', 'zzz', '23'])  
SetA-SetB set(['the', '+', '3', 'pop', '-=\\/'])  
SetA^SetB set(['zzz', '23', 'cuz I can', '+', 'pop', '3', 'the', '-=\\/'])  
SetB^SetA set(['3', 'zzz', '23', 'cuz I can', '+', 'the', 'pop', '-=\\/'])

-  
Dictionaries({'pool':'fun','cool':'drink','fast':'car'}) - a collection of strings or numbers as keys, paired with other strings or numbers as values, as a way for looking up the values.

Pages={'Apples':'good','black oil':'bad','green floor':'questionable'}  
Pages {'green floor': 'questionable', 'black oil': 'bad', 'Apples': 'good'}  
Pages['Apples']  
'good'  
{6:7,8:9}[8]  
9

-  
Cannot concatenate(add) numbers and strings:  
7+'7'

Traceback (most recent call last):  
File "pyshell#8", line 1, in module  
7+'7'  
TypeError: unsupported operand type(s) for +: 'int' and 'str'

[4,77,99]+'cooler'

Traceback (most recent call last):  
File "pyshell#6", line 1, in module  
[4,77,99]+'cooler'  
TypeError: can only concatenate list (not "str") to list ['coocoo']+5

Traceback (most recent call last):  
File "pyshell#9", line 1, in module  
['coocoo']+5 TypeError: can only concatenate list (not "int") to list

-  
OPERATORS: Performs an action on a value(such as on a string or number).

assignment operator:  
= Assigns a value to a variable.  
value='Cool stuff.'  
value 'Cool stuff.'  
number=7568 number 7568

Arithmetic operators:  
Symbol Name + Addition - Subtraction * Multiplication / Division / Floor division % Modulo ** Power

Boolean operators:  
and or not

Relational Operators Symbol Meaning strictly less than = less than or equal to greater than = greater than or equal to == equal to != or not equal to is object identity is not negated object identity

Bitwise operators Symbol Meaning ~ bitwise negation ^ bitwise exclusive or & bitwise and | bitwise or left shift right shift

Compound assignment operators += -= *= /= /= %= **= &= |= ^= = =

Operator precedence(first to last):  
unary + - ~ **

&  
^ | = == = != is not and or

Associativity:  
Arithmetic, boolean, relational and bitwise operators are all left to right associated.  
The assignment operator is right associated.  
The compound assignment operators are right to left associated.

-  
The use of ``

supernumber=78 supernumber+8 86 'I am ' + `supernumber` + '.'  
'I am 78.'  
supernumber + ' is a number.'

Traceback (most recent call last):  
File "pyshell#93", line 1, in module  
'I am ' + supernumber TypeError: cannot concatenate 'str' and 'int' objects

== checks for a value in a variable.

rock='pet'  
rock=='k'  
False rock=='pet'  
True

KEYWORDS:

and - sets two conditions, which must be true for an action to be performed.  
compares=7 if compares 5 and compares 9:  
print '7 is good number'

7 is good number if compares -99 and compares 6:  
print '7 is bad number'

as assert break class continue def -  
del - deletes a defined element of a list.  
popa=[6,8,45,900,67]  
del popa[3]  
popa [6, 8, 45, 67]

popa= (7,8,9)  
del popa[0]

Traceback (most recent call last):  
File "pyshell#9", line 1, in module  
del popa[0]  
TypeError: 'tuple' object doesn't support item deletion

-  
elif - rock='pet'  
if rock=='lava':  
print 'PAINNNNN!'  
elif rock=='magma':  
print 'Double Pain!'  
elif rock=='pet':  
print 'All is forgiven.'  
else:  
print 'I give.'

All is forgiven.

else - if a condition is not met, the the specifies what action will be done instead.  
rock='pet'  
if rock=='lava':  
print 'Pain!'  
else:  
print 'That\'s a good rock.'

That's a good rock.

except exec finally for from global -  
if - sets a condition as something that must be true in order to perform a task.  
rock='pet'  
if rock=='pet':  
print 'No rocks allowed!'

No rocks allowed!

import -  
in - Checks for Membership (Checks if something is in a string).

zoo='monkey man'  
'm' in zoo True 'a' in 'a good four years'  
True 'l' in zoo False fool=345 4 in fool

Traceback (most recent call last):  
File "pyshell#23", line 1, in module  
4 in fool TypeError: argument of type 'int' is not iterable 'lov'in'love'  
True

is - checks is two variables are the same, not just equal to.  
test=quiz='answer please'  
test is test True test is quiz True test == quiz True fail=88 ure=88 fail==ure True fail is ure True fail=[7,8,9]  
ure=[7,8,9]  
fail is ure False fail == ure True fail is ure False -  
lambda not -  
or - sets two conditions, in which at least one of them must be met in order for a specified action to take place.  
compares = 7 if compares 1 or compares == 8:  
print 'you may pass'

you may pass if compares 9 or compares 11:  
print 'Wow...'  
else: print 'HA! I knew it!'

HA! I knew it!  
if compares == 7 or compares != 8:  
print '7 doesn\'t equal 8'

7 doesn't equal 8 -  
pass -  
print - displays strings without the outer most quotation marks.  
print 'hop up there'  
hop up there -  
raise return try while with yield -  
Nesting Statements:

AA='b'='B'  
SyntaxError: can't assign to literal AA=BB='ab'  
if AA=='ab':  
if BB=='mm':  
print'weird stuff'  
else:print 'that makes more sense'  
else: print 'that\'s right out'

that makes more sense

-  
Functions - a word, followed by a parameter in parentheses ()

Python's built-in functions:

abs() - the absolute value of a number.  
abs(3)  
3 abs(-9)  
9 abs(0)  
0

all()  
any()

basestring()  
bin()  
bool()  
bytearray()

callable()  
chr()  
classmethod()  
cmp()  
compile()  
complex()

delattr()  
dict()  
dir()  
divmod()

enumerate()  
eval()  
execfile()

file()  
filter()  
float()  
format()  
frozenset()

getattr()  
globals()

hasattr()  
hash()  
help()  
hex()

id()

input() - lets user input a value. Use for numbers(or strings if you put '' around them).  
an_input=input('prompt ')  
prompt 9 an_input+6 15 age=input('type your age here: ')  
type your age here: 779 age+8 787 letter=input()  
'h'  
letter 'h'  
letter=input()  
h

Traceback (most recent call last):  
File "pyshell#18", line 1, in module  
letter=input()  
File "string", line 1, in module  
NameError: name 'h' is not defined

name=input('enter your name here: ')  
enter your name here: 'Bill'  
name 'Bill'

-  
int()  
isinstance()  
issubclass()  
iter()

len() - shows the number of elements there are in a sequence or string.  
numbers=[3,3,6,7,7,8,44,94532]  
len(numbers)  
8 len('hello')  
5

list() - turns the indiviual characters of a string into an element of a sequence.  
list('leg T')  
['l', 'e', 'g', ' ', 'T']

-  
locals()  
long()

map()

max() - checks the largest number in a sequence, or the hightest letter in a string, or the highest word in a sequence.  
max([6,8,3,7,99,45])  
99 max('key')  
'y'  
max(('hey','look','moomoomilk'))  
'moomoomilk'

-  
memoryview()

min() - checks the smallest number in a sequence, or the lowest letter in a string, or the lowest word in a sequence.  
min((8,-5,0))  
-5 min('key')  
'e'  
min(['hey', 'now', 'zoo'])  
'hey'

-  
next()

object()  
oct()  
open()  
ord()

pow() - another way to perform the power orperator 7**8 5764801 pow(7,8)  
5764801

print()  
property()

range()

raw_input() - lets user input a value. Use for strings.  
ID=raw_input("enter name: ")  
enter name: Cane ID 'Cane'

number=raw_input()  
9 print number 9 9+number

Traceback (most recent call last):  
File "pyshell#6", line 1, in module  
9+number TypeError: unsupported operand type(s) for +: 'int' and 'str'

reduce()  
reload()  
repr() - similar to str()  
reversed()  
round()

set()  
setattr()  
slice()  
sorted()  
staticmethod()

str() - sets something as a string.  
coolnumber=str(4)  
coolletter=str(j)

Traceback (most recent call last):  
File "pyshell#84", line 1, in module  
coolletter=str(j)  
NameError: name 'j' is not defined coolletter=str('j')  
print coolnumber+coolletter 4j

sum()  
super()

tuple()  
type()

unichr()  
unicode()

vars()

xrange()

zip()

_import_()

apply()

buffer()

coerce()

intern()

-  
Modules -

import math

-  
Methods - an action to perform on an object. The object is followed by a float and then a method, followed by an argument in parenthesis.

append - adds an element at the end of a list.  
handy=[1,000,69,77778,8,0]  
handy[1]  
0 (1000)  
handy [1, 0, 69, 77778, 8, 0, 1000]  
(6,7,8)

Traceback (most recent call last):  
File "pyshell#4", line 1, in module  
(6,7,8)  
TypeError: append() takes exactly one argument (3 given)

-  
clear - clears a dictionary.  
loop={8:9,88:89,99:100}

loop {}

-  
copy - copy a dictionary to another.  
loop={7:8,9:10}  
loopy= ()  
loopy {7:8, 9:10}

-  
count - checks the number of one type of specified element there are in a sequence.  
flower= ('0','ghostly','hat','hat','hat')  
('hat')  
3

extend - can add multible values at the end of a list.  
hi=[0,9,6,44,8]  
bye=[7,9]  
(bye)  
hi [0, 9, 6, 44, 8, 7, 9]

-  
find - finds the place of the first character of a specified string in a string.  
'You love to drink milk.'.find('milk')  
18

has_key - checks if a dictionary has a specified key in it.  
Pages={'Apples':'good','black oil':'bad','green floor':'questionable'}  
_key('good')  
False _key('black oil')  
True

index - tells where an element is in a sequence.  
keep=['laa','h','what?','oh!']  
('what?')  
2 -  
insert - inserts an element into a specified place in a list.  
tower=[88,89,1001,7,9998]  
(1,77)  
tower [88, 77, 89, 1001, 7, 9998]

join - inserts a string inbetween each element of a sequence containing other strings, and makes it all one string.  
mix_up=['Time','for','failure']  
inthere='LA'  
(mix_up)  
'TimeLAforLAfailure'  
inthere=' '  
(mix_up)  
'Time for failure'

-  
lower - changes upper cases of a string into lower cases.  
'Love Is cOoL.'.lower()  
'love is cool.'

-  
pop - pops out an element from a list and returns it to you.  
tower=[88,89,1001,7,9998]  
(3)  
7 tower [88, 89, 1001, 9998]

-  
remove - removes a specified element from a list.  
tower=[88,89,1001,7,9998]  
(1001)  
tower [88, 89, 9998]

-  
reverse - reverses a list.  
keep=['laa','h','what?','oh!']

keep ['oh!', 'what?', 'h', 'laa']

-  
replace - replaces characters in a string with other ones.  
'Hoohaa! La la! What!'.replace('!','?')  
'Hoohaa? La la? What?'

-  
sort - In a list, puts numbers in order and strings in alphabetical order.  
hook=[5,3,3,89,3,1,1999,55]

hook [1, 3, 3, 3, 5, 55, 89, 1999]  
looking=['j','m','a','b','J']  
built-in method sort of list object at 0x00000000034C8408

looking ['J', 'a', 'b', 'j', 'm']

-"

"Bbbooorrrrrriiiiinnnngggggg!" shouted Pinkie, while Dash fell asleep.

"Guys, come on! You said you wanted to make a video game. You'll need to learn a programming language in order to do that. And python is ideal." Twilight yelled in frustration.

"Can't you make a game for us? And we'll tell you what to put in it?" suggested Pinkie Pie.

"I'm trying to install some sort of sophisticated knowledge in you two. But I suppose that was too much to ask." The purple unicorn sighed.

Will Pinkie and Dashie ever make a video game? If so, what would be like? I shutter.

To be continued.


End file.
